-- FUNCTION: public.widget_GetPharmacySaleAmountByDate(date, integer, integer)

-- DROP FUNCTION IF EXISTS public."widget_GetPharmacySaleAmountByDate"(date, integer, integer);

CREATE OR REPLACE FUNCTION public."widget_GetPharmacySaleAmountByDate"(
	"fromDate" date DEFAULT NULL::date,
	"referenceId" integer DEFAULT NULL::integer,
	"locationId" integer DEFAULT NULL::integer)
    RETURNS TABLE("Count" numeric) 
    LANGUAGE 'plpgsql'
    COST 100
    VOLATILE PARALLEL UNSAFE
    ROWS 1000

AS $BODY$
BEGIN
return query
with cts as ( SELECT PP."CategoryId",LV."Name" as "CategoryName",SUM(PSD."NetAmount") as "SaleAmount",COALESCE(b.NetAmount, 0) as "RetrunAmount",SUM(PSD."NetAmount") - COALESCE(b.NetAmount, 0) as "TotalAmount"
                        FROM "PharmacySaleDetail" PSD
                        JOIN "PharmacyProduct" PP ON PP."PharmacyProductId" = PSD."PharmacyProductId"
                        JOIN "LookupValue" LV ON LV."LookupValueId" = PP."CategoryId"
			 			left JOIN "PharmacySaleHeader" PSH ON PSH."PharmacySaleHeaderId"=PSD."PharmacySaleHeaderId"
                        LEFT JOIN (select SUM(SRD."NetAmount")NetAmount,SRD."PharmacyProductId"  from "SaleReturnDetail" SRD 
					   join "SaleReturnHeader" SRH on SRH."SaleReturnHeaderId"=SRD."SaleReturnHeaderId"
					   where SRH."ReturnDate"::date ="fromDate" 
								   GROUP BY SRD."PharmacyProductId") B on
                        B."PharmacyProductId" = PSD."PharmacyProductId"
			 			left join "Provider" pr on pr."ProviderId"= PSH."ProviderId"
						left join "ProviderLocation" PL on PL."ProviderId"=pr."ProviderId" and case when "locationId" is null then 1=1 else  PL."LocationId"= "locationId" end
						left join "Account" PA on PA."ReferenceId"=pr."ProviderId"  and PA."RoleId"=3
						where case when "fromDate" is null then 1=1 else PSH."SaleDate"::date = "fromDate" end
						and case when "locationId" is null then 1=1 else PSH."LocationId"= "locationId" end
			 			and case when "referenceId" is null then 1=1 else PA."ReferenceId"= "referenceId" end
                        group by PP."CategoryId",LV."Name",b.NetAmount
                        ),
                        salesTotal as (
                        select 
                         COALESCE(SUM( a."TotalAmount"),0) as "Count"
                        from cts a)
						select c.* from salesTotal c;
						
END
$BODY$;

ALTER FUNCTION public."widget_GetPharmacySaleAmountByDate"(date, integer, integer)
    OWNER TO postgres;